/**
 * Created by lvlq on 16/3/16.
 */
var csv = require("csv");
var sequelize = Util("sequelize");

module.exports.exportCSV = function (req, res) {
    var pid = req.query.pid;

    var Result = M("index.result");

    var alldata = [];
    Result.findAll({
        where: {
            pid: pid
        },
        attributes: ["id", "openid", "nickname", "headimgurl", "pid", "pname", "name", "phone", [sequelize.fn("date_format", sequelize.col('createdAt'), '%Y-%m-%d %H:%m:%s'), "time"]],
    }).then(function (data) {
        for (var i = 0; i < data.length; i++) {
            var val = data[i].nickname;
            var s = new Buffer(val, 'base64').toString();
            data[i].nickname = s;

            if (data[i].id >= 126) {
                var val1 = data[i].nickname;
                var s1 = new Buffer(val1, 'base64').toString();
                data[i].nickname = s1;
            }
        }
        alldata = data;
        var title = {
            id: "id",
            openid: "微信openid",
            nickname: "微信昵称",
            headimgurl: "微信头像",
            pid: "奖品id",
            pname: "奖品名称",
            name: "姓名",
            phone: "手机号",
            time: "申请时间"
        };
        alldata.unshift(title);

        var Prize = M("index.prize");
        return Prize.find({
            where: {
                id: pid
            }
        });
    }).then(function (data) {
        var name = encodeURI(data.name + '获奖数据');
        res.setHeader('Content-disposition', 'attachment; filename=' + name + '.csv');
        res.writeHead(200, {'Content-Type': 'text/csv'});
        csv.stringify(alldata, function (err, d) {
            var iconv = require('iconv-lite');
            var str = iconv.encode(d, 'gb2312');
            res.write(str);
            res.end();
        })
    });
};

module.exports.exportCSV1 = function (req, res) {
    var UserList = M("index.userList");
    var ActiveList = M("index.activeList");

    var aid = req.query.aid;
    var alldata = [];
    UserList.findAll({
        where: {
            aid: aid
        },
        attributes: ["id", "name", "phone", "address", "pname", "img_url", "ac_code", "createdAt", sequelize.fn("date_format", sequelize.col('createdAt'), '%Y-%m-%d %H:%m:%s')]
    }).then(function (data) {
        alldata = data;
        var title = ["id", "姓名", "手机号", "地址", "奖品名", "图片链接", "数码", "创建时间"];
        alldata.unshift(title);

        return ActiveList.find({
            where: {
                id: aid
            }
        });
    }).then(function (data) {
        var name = encodeURI(data.name + '获奖数据');
        res.setHeader('Content-disposition', 'attachment; filename=' + name + '.csv');
        res.writeHead(200, {'Content-Type': 'text/csv'});
        csv.stringify(alldata)
            .pipe(res);
    });
};

